<template>
  <el-dialog
    v-model="visible"
    width="700px"
    :before-close="handleClose"
    class="unified-dialog job-restart-dialog"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon header-icon-success">
          <el-icon><Refresh /></el-icon>
        </div>
        <div class="header-content">
          <h3>重启作业</h3>
          <p>重新启动Flink作业并应用新参数</p>
        </div>
      </div>
    </template>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="作业名称">
        <el-input :value="job?.job_name" disabled />
      </el-form-item>
      
      <el-form-item label="JAR包">
        <el-input :value="job?.jar_name" disabled />
        <span class="form-tip">JAR包信息从数据库自动加载</span>
      </el-form-item>
      
      <el-form-item label="入口类">
        <el-input :value="job?.entry_class" disabled />
        <span class="form-tip">入口类信息从数据库自动加载</span>
      </el-form-item>
      
      <el-form-item label="程序参数" prop="program_args">
        <el-input
          v-model="form.program_args"
          type="textarea"
          :rows="6"
          placeholder="请输入程序启动参数，例如：--parallelism 2 --env test --timestamp 1756958400000"
        />
        <div class="param-templates">
          <el-button size="small" @click="applyTemplate('basic')">基础参数</el-button>
          <el-button size="small" @click="applyTemplate('test')">测试环境</el-button>
          <el-button size="small" @click="applyTemplate('dev')">开发环境</el-button>
          <el-button size="small" @click="applyTemplate('timestamp')">带时间戳</el-button>
          <el-button size="small" type="primary" @click="showTimestampPicker">
            <el-icon><Clock /></el-icon>
            生成时间戳
          </el-button>
        </div>
      </el-form-item>
      
      <el-form-item label="Flink环境">
        <el-select
          v-model="form.flink_env"
          placeholder="选择Flink环境"
          clearable
          filterable
          style="width: 100%"
          popper-class="batch-dialog-select-popper"
          :teleported="true"
        >
          <el-option
            v-for="env in environmentOptions"
            :key="env.value"
            :label="`${env.label} (${env.host}:${env.port})`"
            :value="env.value"
          />
        </el-select>
        <span class="form-tip">选择Flink环境，留空使用默认环境</span>
      </el-form-item>
      
      <el-form-item label="更新数据库">
        <el-switch
          v-model="form.update_db"
          active-text="是"
          inactive-text="否"
        />
        <span class="form-tip">多环境场景建议关闭，避免数据混乱</span>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定重启
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 时间戳选择器弹窗 -->
  <el-dialog
    v-model="timestampPickerVisible"
    title="选择时间戳"
    width="500px"
    :close-on-click-modal="false"
    :append-to-body="true"
    :modal="true"
    :modal-append-to-body="true"
    :z-index="3000"
    destroy-on-close
  >
    <div class="timestamp-picker">
      <el-alert
        title="时间戳说明"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 20px"
      >
        <template #default>
          <p>选择的时间将转换为毫秒时间戳并插入到参数中</p>
        </template>
      </el-alert>
      
      <el-form label-width="100px">
        <el-form-item label="选择日期">
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
            :clearable="true"
            @change="handleDateChange"
            style="width: 100%"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          />
        </el-form-item>
        
        <el-form-item label="选择时间">
          <el-time-picker
            v-model="selectedTime"
            placeholder="选择时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :clearable="true"
            @change="handleTimeChange"
            style="width: 100%"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          />
        </el-form-item>
        
        <el-form-item label="时间戳预览">
          <el-input
            :value="timestampPreview"
            readonly
            placeholder="选择日期和时间后显示时间戳"
          />
        </el-form-item>
        
        <el-form-item label="参数预览">
          <el-input
            :value="paramPreview"
            type="textarea"
            :rows="3"
            readonly
            placeholder="预览插入时间戳后的完整参数"
          />
        </el-form-item>
        
        <el-form-item label="快捷选择">
          <div class="quick-select-buttons">
            <el-button size="small" @click="setQuickTime('1h')" plain>1小时前</el-button>
            <el-button size="small" @click="setQuickTime('6h')" plain>6小时前</el-button>
            <el-button size="small" @click="setQuickTime('12h')" plain>12小时前</el-button>
            <el-button size="small" @click="setQuickTime('today')" plain>今天开始</el-button>
            <el-button size="small" @click="setQuickTime('yesterday')" plain>昨天开始</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="timestampPickerVisible = false">取消</el-button>
        <el-button type="primary" @click="insertTimestamp">插入时间戳</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useJobsStore } from '@/stores/jobs'
import { useAppStore } from '@/stores/app'
import { useFlinkEnvStore } from '@/stores/flinkEnv'
import { ElMessage } from 'element-plus'
import { componentLogger } from '@/utils/logger'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  job: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const jobsStore = useJobsStore()
const appStore = useAppStore()
const flinkEnvStore = useFlinkEnvStore()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref()
const loading = ref(false)

// 环境选项
const environmentOptions = computed(() => flinkEnvStore.getEnvironmentOptions())

const form = ref({
  program_args: '',
  flink_env: '',
  update_db: false  // 默认不更新数据库
})

// 时间戳选择器相关状态
const timestampPickerVisible = ref(false)
const selectedDate = ref('')
const selectedTime = ref('')

// 日期快捷选择配置
const dateShortcuts = [
  {
    text: '今天',
    value: () => new Date()
  },
  {
    text: '明天',
    value: () => {
      const tomorrow = new Date()
      tomorrow.setDate(tomorrow.getDate() + 1)
      return tomorrow
    }
  },
  {
    text: '后天',
    value: () => {
      const dayAfterTomorrow = new Date()
      dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2)
      return dayAfterTomorrow
    }
  }
]

const rules = {
  // JAR包和入口类从数据库自动加载，无需验证
}

const handleClose = () => {
  visible.value = false
}

const initForm = () => {
  if (props.job) {
    form.value = {
      program_args: props.job.program_args || '',
      flink_env: ''
    }
  }
}

// JAR包和入口类从数据库自动加载，无需额外加载

// 参数模板
const paramTemplates = {
  basic: '--parallelism 1 --env dev',
  test: '--parallelism 2 --env test',
  dev: '--parallelism 1 --env dev',
  timestamp: `--parallelism 1 --env test --timestamp ${Date.now()}`
}

const applyTemplate = (templateKey) => {
  const template = paramTemplates[templateKey]
  if (template) {
    form.value.program_args = template
    ElMessage.success(`已应用${templateKey}参数模板`)
  }
}

// 时间戳相关计算属性
const timestampPreview = computed(() => {
  if (!selectedDate.value || !selectedTime.value) return ''
  const dateTimeStr = `${selectedDate.value} ${selectedTime.value}`
  const timestamp = new Date(dateTimeStr).getTime()
  return timestamp.toString()
})

const paramPreview = computed(() => {
  if (!selectedDate.value || !selectedTime.value) return ''
  const dateTimeStr = `${selectedDate.value} ${selectedTime.value}`
  const timestamp = new Date(dateTimeStr).getTime()
  const timestampStr = `--timestamp ${timestamp}`
  
  const currentArgs = form.value.program_args.trim()
  if (!currentArgs) {
    return timestampStr
  }
  
  if (currentArgs.includes('--timestamp')) {
    return currentArgs.replace(/--timestamp\s+\d+/g, `--timestamp ${timestamp}`)
  } else {
    return currentArgs + ' ' + timestampStr
  }
})

// 显示时间戳选择器
const showTimestampPicker = () => {
  // 设置默认时间为当前时间
  const now = new Date()
  selectedDate.value = now.toISOString().slice(0, 10)
  selectedTime.value = now.toTimeString().slice(0, 8)
  timestampPickerVisible.value = true
}

// 处理日期变化
const handleDateChange = (value) => {
  componentLogger.info('日期选择器变化:', value)
  if (value) {
    componentLogger.info('选择的日期:', value)
  }
}

// 处理时间变化
const handleTimeChange = (value) => {
  componentLogger.info('时间选择器变化:', value)
  if (value) {
    componentLogger.info('选择的时间:', value)
  }
}

// 快捷时间选择
const setQuickTime = (type) => {
  const now = new Date()
  let targetTime
  
  switch (type) {
    case '1h':
      targetTime = new Date(now.getTime() - 1 * 60 * 60 * 1000)
      break
    case '6h':
      targetTime = new Date(now.getTime() - 6 * 60 * 60 * 1000)
      break
    case '12h':
      targetTime = new Date(now.getTime() - 12 * 60 * 60 * 1000)
      break
    case 'today':
      targetTime = new Date(now)
      targetTime.setHours(0, 0, 0, 0)
      break
    case 'yesterday':
      targetTime = new Date(now)
      targetTime.setDate(now.getDate() - 1)
      targetTime.setHours(0, 0, 0, 0)
      break
    default:
      targetTime = now
  }
  
  // 设置日期和时间
  selectedDate.value = targetTime.toISOString().split('T')[0]
  selectedTime.value = targetTime.toTimeString().split(' ')[0]
  
  const labels = {
    '1h': '1小时前',
    '6h': '6小时前',
    '12h': '12小时前',
    'today': '今天开始',
    'yesterday': '昨天开始'
  }
  ElMessage.success(`已设置为${labels[type] || '未知'}`)
}

// 插入时间戳
const insertTimestamp = () => {
  if (!selectedDate.value || !selectedTime.value) {
    ElMessage.warning('请先选择日期和时间')
    return
  }
  
  const dateTimeStr = `${selectedDate.value} ${selectedTime.value}`
  const timestamp = new Date(dateTimeStr).getTime()
  const timestampStr = `--timestamp ${timestamp}`
  
  const currentArgs = form.value.program_args.trim()
  if (!currentArgs) {
    form.value.program_args = timestampStr
  } else {
    if (currentArgs.includes('--timestamp')) {
      form.value.program_args = currentArgs.replace(/--timestamp\s+\d+/g, `--timestamp ${timestamp}`)
    } else {
      form.value.program_args = currentArgs + ' ' + timestampStr
    }
  }
  
  timestampPickerVisible.value = false
  ElMessage.success(`已插入时间戳: ${timestamp}`)
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    await jobsStore.restartJob(props.job.job_name, {
      program_args: form.value.program_args,
      flink_env: form.value.flink_env || undefined,
      update_db: form.value.update_db  // 传递数据库更新标志
    })
    
    emit('success')
    handleClose()
  } catch (error) {
    componentLogger.error('重启作业失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听对话框显示状态
watch(visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 监听job变化
watch(() => props.job, () => {
  if (visible.value) {
    initForm()
  }
}, { deep: true })

// 组件挂载时加载环境配置
onMounted(() => {
  flinkEnvStore.fetchFlinkEnvironments()
})
</script>

<style scoped>
/* 对话框已使用统一样式系统 (dialog-system.css) */

.form-tip {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

.param-templates {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.param-templates .el-button {
  font-size: 12px;
  padding: 4px 8px;
  height: auto;
  border-radius: 6px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 时间戳选择器样式 */
.timestamp-picker {
  padding: 10px 0;
  position: relative;
  z-index: 1;
}

/* 确保对话框footer可点击 */
.timestamp-picker ~ .dialog-footer {
  position: relative;
  z-index: 10;
}

:deep(.el-dialog__footer) {
  position: relative;
  z-index: 10;
  pointer-events: auto !important;
}

:deep(.el-dialog__footer .el-button) {
  pointer-events: auto !important;
}

/* 环境选项样式 */
.env-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.env-name {
  font-weight: 500;
  color: #303133;
}

.env-url {
  font-size: 12px;
  color: #909399;
}

.timestamp-picker .el-form-item {
  margin-bottom: 20px;
}

.timestamp-picker .el-input.is-disabled .el-input__wrapper {
  background-color: #f5f7fa;
  color: #606266;
}

/* 表单项样式优化 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  color: #303133;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  resize: vertical;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

:deep(.el-textarea__inner:hover) {
  border-color: #409eff;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #85ce61 0%, #67c23a 100%);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
}

/* 快捷选择按钮样式 */
.quick-select-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-select-buttons .el-button {
  border-radius: 16px;
  padding: 6px 16px;
  font-size: 13px;
  transition: all 0.3s ease;
  border: 1px solid #dcdfe6;
  background: #ffffff;
  color: #606266;
}

.quick-select-buttons .el-button:hover {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border-color: #409eff;
  color: #ffffff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.quick-select-buttons .el-button:active {
  transform: translateY(0);
}
</style>
